package cn.qio.channel.session;

import java.io.IOException;
import java.nio.channels.SelectionKey;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.UUID;

import cn.qio.channel.handler.ChannelHandler;
import cn.qio.event.EventDispatcher;

/**
 * 通道 session
 * 
 * @author chenhua
 *
 */
public class ChannelSession {

	private final String sessionId;

	private final EventDispatcher eventDispatcher;

	private final SocketChannel socketChannel;

	private final ArrayList<ChannelHandler> eventHandlers;

	public ChannelSession(SocketChannel socketChannel, EventDispatcher eventDispatcher,
			ArrayList<ChannelHandler> eventHandlers) {
		this.eventDispatcher = eventDispatcher;
		this.socketChannel = socketChannel;
		this.eventHandlers = eventHandlers;
		this.sessionId = UUID.randomUUID().toString();
	}

	/**
	 * 启动这个session
	 * 
	 * @throws IOException
	 */
	public void start() throws IOException {
		System.out.println("start a new connect...");
		socketChannel.configureBlocking(false);
		eventDispatcher.register(this, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
	}

	public String getSessionId() {
		return sessionId;
	}

	public EventDispatcher getEventDispatcher() {
		return eventDispatcher;
	}

	public SocketChannel getSocketChannel() {
		return socketChannel;
	}

	public ArrayList<ChannelHandler> getEventHandlers() {
		return eventHandlers;
	}

}
